//
//  HomeViewController.swift
//  WeiBoSwift
//
//  Created by rong on 15/6/24.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit
import SVProgressHUD


 //let strId = "weibo"

class HomeViewController: BaseTableViewController {
    
   // static let strId = "weibo"

    //表格绑定的微博数据
    var statusList: [Status]? {
    
        didSet{
        
            //重新刷新表格数据
            tableView.reloadData()
            
            //刷新完成后，关闭刷新控件
            //refreshControl?.endRefreshing()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

       visitorView?.setupViewInfo("visitordiscover_feed_image_house", introduce: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
       
        //!!!!一下代码是用户登录之后才运行的代码,如果没有登录，直接返回
        if !userLogin {
            return
        }
        
        setupNavigationBar()
        
        prepareForTableView()
        prepareForRefreshControl()
    }
    
    
    private func prepareForTableView() {
        //注册 可重用的  cell, 两种都注册
        tableView.registerClass(StatusTransmitCell.self, forCellReuseIdentifier: StatusTransmitCellIdentifier)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusNormalCellIdentifier)
        
        
        //预估行高能够 减少行高计算的频率
        //tableView.estimatedRowHeight = 200    !!!!!! 设置缓存行高之后，就不能设置这句话了
        //tableView.rowHeight = 500//UITableViewAutomaticDimension
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    private func prepareForRefreshControl() {
        
        //刷新特效
        refreshControl = MyRefreshContrl()
        //refreshControl = UIRefreshControl()
        
        //addTarget的方法，不能是private, 程序会崩掉
        refreshControl?.addTarget(self, action: "loadWeiboData", forControlEvents: UIControlEvents.ValueChanged)
        
        //加载微博数据
        loadWeiboData()
        
        //开启动画, 如果放在这里，界面一切换，再回到这个界面的时候，就不会再转了
        //visitorView?.startAnimation()
        //print("HomeViewController ==> viewDidLoad")

    }
    
    //上拉刷新标记
    private var pullRefreshFlag = false
    
    //加载微博数据
     func loadWeiboData(){
        
        refreshControl!.beginRefreshing()
    
        //下拉刷新的代号，取到数组中的第一条数据的ID
        var since_id = statusList?.first?.id ?? 0
         var max_id = 0
        
        if pullRefreshFlag {
            since_id = 0
            max_id = statusList?.last?.id ?? 0
        }
        
        Status.loadStatus(since_id, max_id: max_id) { (statues, error) -> () in
            
            //！！！如果不放在这里，下面的两个错误return之后，就不会走 statusList 的setter方法，就不停止刷新控件
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            //其中一种情况是，下拉刷新的时候，没有数据返回
            if statues == nil {
                print("微博没有数据返回")
                return
            }
            
            //判断是否是下拉刷新，如果是，将最新的数据添加到 statusList 的前面，
            if since_id > 0 {
                
                self.statusList = statues! + self.statusList!
            } else if max_id > 0 {
                
                self.statusList = self.statusList! + statues!
                //上拉刷新结束之后，改变标志位
                self.pullRefreshFlag=false
            } else {
                
                //这是初始刷新
                self.statusList = statues
            }

        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        //如果放在这里，界面切换回来的时候会调用这个函数，切换到这个界面会继续转动
        visitorView?.startAnimation()
       // print("viewDidAppear")
    }

    
    //设置NavigationBar
    private func setupNavigationBar()
    {
        //判断用户是否登录
        if sharedUserAccount == nil{
            
            //如果没有登录，直接返回
            return
        }
        
        //1.设置"左右"按钮
        //导航栏 左边的
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: "navigationbar_friendsearch_highlighted")
        
        //导航栏 右边的
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: "navigationbar_pop_highlighted")
        
        //给右边的添加点击事件
        let rightBtn = navigationItem.rightBarButtonItem!.customView as! UIButton
        rightBtn.addTarget(self, action: "QRCodeShow", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        //2.设置“中间”标题
        let titleBtn = HomeTitleButton.button(sharedUserAccount!.name!)
        titleBtn.addTarget(self, action: "titleButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    
    //显示“扫一扫”界面
    func QRCodeShow(){
    
       //用storyboard创建的不能直接这样使用 presentViewController(QRCodeViewController(), animated: true, completion: nil)
        let vc = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(vc.instantiateInitialViewController()!, animated: true, completion: nil)
    }
    
    //动画的转场代理
     let popoverAnimator = PopoverAnimator()
    
    //中间按钮点击触发事件 
    //#pragma warning 为什么加上private不行，报错
    func titleButtonClicked(){
        
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroup")
        
        //1.设置转场代理
        vc.transitioningDelegate = popoverAnimator
        
        //后添加的，设置视图的展现大小
        let originX = (view.bounds.width - 200) * 0.5
        popoverAnimator.presentFrame = CGRectMake(originX, 56, 200, 300)
        //2.设置转场的模式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        //modal方式，出现界面，此时后面的界面已经消失
        presentViewController(vc, animated: true, completion: nil)
    
    }
    
    //是展现还是消失 的标记
    //var isPresented = false
    
    
    //tableviewde代理方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusList?.count ?? 0
    }
    
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        //1.首先获取数据模型
        let status = statusList![indexPath.row]
        
        //2. 根据数据获取相应的 cell标识符
        let cellID = StatusCell.cellIdentifier(status)
        
        //用这种方式， 必须注册
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! StatusCell
        
        cell.status = status
        
        cell.statusCellDelegate = self
        
        //print("hhhhhhhhhhh => ")
        //print(statusList![indexPath.row].user!.name)
        
        //如果到了最后一条微博，自动下拉刷新
        if indexPath.row == statusList!.count - 1 {
        
            pullRefreshFlag = true
            loadWeiboData()
        }
        
        return cell
    }
    
    
    //行高缓存
    lazy var rowHeightCache = [Int: CGFloat]()
    
    //计算行高的函数
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        //取到对象
        let status = statusList![indexPath.row]
        
        if rowHeightCache[status.id] != nil {
            print("返回的是缓存的行高")
            
            return rowHeightCache[status.id]!
        }
        
        //根据数据获取相应的 cell标识符
        let cellID = StatusCell.cellIdentifier(status)
        
        //获取cell -----> 从缓冲池中提取一个cell，说明之前用过，  ！！！但是如果想准确计算一个行高，需要实例化一个cell
        // 在 Xcode6.0 不存在这个问题，Xcode7.0 新发现的
        //let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! StatusCell
        
        
        //!!!!  解决方法： 定义一个类，默认是原创微博的类
        var cls: AnyClass = StatusNormalCell.self
        if cellID == StatusTransmitCellIdentifier {
            cls = StatusTransmitCell.self
        }
        
        let cell = cls.new() as! StatusCell
        
        //返回行高
        let rowHeight = cell.picCellRowHeight(status)
        
        rowHeightCache[status.id] = rowHeight
        
        return rowHeight
        
    }
    
    //如果出现内存警告，删除行高缓存
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        //如果用的NSCacle,不能这样清空
        rowHeightCache.removeAll()
    }
    
    
    //是否转场标记
    var isPresented = false
    
    //需要两个变量
    //临时的图片视图
    private lazy var presentedImageView = UIImageView()
    //目标位置
    private var presentedFrame = CGRectZero
   
}


// 点击  微博图片 列表中的 某张图片  的协议
extension HomeViewController: StatusCellDelagate {


    
    //StatusCell点击协议
    func statusCellDidSelectedPicture(cell: StatusCell, picIndex: Int){
        
        //print("StatusCell点击协议 ===>")
        //print(cell.status!.picURLs![picIndex])
       
        if cell.status?.largePicUrls == nil{
            return
        }
        
        let vc = PictureBrowserViewController(urls: cell.status!.largePicUrls!, index: picIndex)
        
        //声称一个image view
        presentedImageView.sd_setImageWithURL(cell.status!.largePicUrls![picIndex])
        presentedImageView.frame = cell.getScreenFrame(picIndex)
        presentedFrame = cell.getFullScreenFrame(picIndex)
        
        
        //目前是从下往上modal出来的，需要改成  渐变出现
        //步骤：1.设置转场代理    2.设置转场样式
        vc.transitioningDelegate = self
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    }

}

extension HomeViewController: UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {

    ///  展现转场
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        return self
    }
    
    ///  解除转场
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let transionView = transitionContext.viewForKey(viewKey)
        if transionView == nil {
            return
        }
        
        // Modal 展现
        if isPresented {
            //目标视图添加到 容器视图
            transitionContext.containerView()?.addSubview(transionView!)
            transionView!.alpha = 0
            
            //添加临时的图片视图
            transitionContext.containerView()?.addSubview(presentedImageView)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
                
                
                //从小图 渐变成 大图
                self.presentedImageView.frame = self.presentedFrame
                
                }) { _ in
                    
                    //完成之后，  “删除临时图片”
                    self.presentedImageView.removeFromSuperview()
                    
                    transionView!.alpha = 1.0
                    
                    transitionContext.completeTransition(true)
            }
        } else {
            transionView!.alpha = 1
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
                transionView!.alpha = 0.0
                }) { _ in
                    transionView!.removeFromSuperview()
                    transitionContext.completeTransition(true)
            }
        }
    }

    
}
